#include "../server.hpp"

class EchoServer
{
private:
    TcpServer _server;

private:
    void OnClosed(const PtrConnection &conn)
    {
        DEBUG_LOG("OnClosed::Close Connection: %p", conn.get());
    }
    void OnConnected(const PtrConnection &conn)
    {
        DEBUG_LOG("OnConnected::New Connection: %p", conn.get());
    }
    void OnMessage(const PtrConnection &conn, Buffer *buf)
    {
        std::string bufstr = buf->ReadAsString(buf->ReadableSize()).c_str();
        DEBUG_LOG("%s", bufstr.c_str());
        buf->ReadMove(buf->ReadableSize());
        std::string echostr = "Server echo: " + bufstr;
        conn->Send(&echostr[0], echostr.size());
        // conn->ShutDown();
    }

public:
    EchoServer(int port)
        :_server(port)
    {
        _server.SetThreadCount(2);
        _server.EnableInactiveRelease(6);
        _server.SetConnectedCallback(std::bind(&EchoServer::OnConnected, this, std::placeholders::_1));
        _server.SetClosedCallback(std::bind(&EchoServer::OnClosed, this, std::placeholders::_1));
        _server.SetMessageCallback(std::bind(&EchoServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
    }

    void Start()
    {
        _server.Start();
    }
};